<template>
  <div class="my-workbench my-wbox">
    <div class="my-workbench__top">
      <h3>宁乡市行政区域图</h3>
      <span>数据截止时间：{{ time }} 24：00</span>
    </div>
    <div class="my-workbench__map" v-loading="loading">
      <div id="main" class="my-workbench__map__map"></div>
    </div>
    <div class="my-workbench__rank" v-loading="loading">
      <div class="my-rank">
        <h3><span>敲门入户排行榜</span></h3>
        <dl>
          <dt>
            <span>乡镇名称</span>
            <span>入户率</span>
          </dt>
          <dd class="t-rolly">
            <ul>
              <li v-for="item in rank.list" :class="{ 'disabled': item.disabled }" @click="onDetail(item)">
                <span>{{ item.townName }}</span>
                <span>{{ item.intoRate }}</span>
              </li>
            </ul>
          </dd>
        </dl>
      </div>
    </div>
    <div class="my-workbench__all" v-loading="loading2">
      <div class="my-rank">
        <h3><span>宁乡市</span></h3>
        <ul>
          <li>总户数：<strong>{{ rank.allData.totalNum ? rank.allData.totalNum : '--' }}</strong></li>
          <li>总入户数：<strong>{{ rank.allData.totalIntoNum ? rank.allData.totalIntoNum : '--' }}</strong></li>
          <li>平均入户率：<strong>{{ rank.allData.totalIntoRate ? rank.allData.totalIntoRate : '--' }}</strong></li>
        </ul>
      </div>
    </div>
  </div>
</template>
<script setup lang='ts'>
import axios from 'axios'
import { ref, reactive, onMounted, watch, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'
import { sortedListApi, totalDataApi } from '@/views/workbench/api/workbenchApi'
import { FunTime } from '@/global/methods'
import { getUserInfo } from '@/global/session'
import { useRouter } from 'vue-router'
const router = useRouter()
let nameMap = {}
let regions = <any>[]
let areaColor: string = '#dcecff'
const rank = reactive({//排行榜
  list: <any>[],
  allData: <{ totalNum: number, totalIntoNum: number, totalIntoRate: string }>{}
})
// const allData=reactive({})
const resize = ref<boolean>(false)
const loading2 = ref<boolean>(false)

let userInfo = reactive({ roleId: '', townId: '', countryId: '', roleAuth: '' })
userInfo = JSON.parse(getUserInfo() as string)

const loading = ref<boolean>(true)
//获取排行榜数据
const onSortedList = async () => {
  try {
    let res = await sortedListApi()
    if (res?.code === 0) {
      res.data.forEach(v => {
        if (userInfo.roleId == '4' || userInfo.roleId == '5') {
          areaColor = '#dcecff'
          v.disabled = true
          if (userInfo.townId === v.townId) {
            v.disabled = false
            regions = [{
              name: v.townName, //区块名称
              itemStyle: {
                areaColor: '#3479d8',
              }
            }]
          }
        } else if (userInfo.roleId == '3') {
          let roleAuth = userInfo.roleAuth.split(',')
          v.disabled = true
          roleAuth.forEach(t => {
            if (t === v.townId) {
              v.disabled = false
              regions.push({
                name: v.townName, //区块名称
                itemStyle: {
                  areaColor: '#7eb4ff',
                }
              })
            }
          })
        }
        Object.assign(nameMap, { [v.townId]: v.townName })
      });
      rank.list = res.data
      onMap()
    } else {
      loading.value = false
    }
  } catch {
    loading.value = false
  }
}
//获取宁乡数据totalDataApi
const onTotalData = async () => {
  try {
    let res = await totalDataApi()
    if (res?.code === 0) {
      rank.allData = res.data
    }
    loading2.value = false
  } catch {
    loading2.value = false
  }
}
loading2.value = true
onTotalData()
//制地图
const onMap = () => {
  axios.get('./newningxiangys.json').then((res) => {
    let geoJson = res.data
    // 基于准备好的dom，初始化echarts实例
    let myChart = echarts.init(document.getElementById('main') as unknown as HTMLDivElement)
    // 绘制图表
    let optionMap = {
      tooltip: {},//鼠标移入
      geo: {
        map: 'NX',//使用 registerMap 注册的地图名称
        //缩放比例
        zoom: 1.25,//当前视角的缩放比例
        scaleLimit: {//滚轮缩放的极限控制，通过min, max最小和最大的缩放值，默认的缩放为1
          min: 1
        },
        nameMap: nameMap,
        nameProperty: 'id', // 数据点中的 name：Alabama 会关联到
        label: {//图形上的文本标签，可用于说明图形的一些数据信息，比如值，名称等。
          show: true,
          color: '#3479d8',
          fontWeight: 'bold',
          fontSize: 12,
          lineHeight: 14,
          // backgroundColor: '#fff',
          // padding: [1, 2],
          textBorderColor: '#fff',
          textBorderWidth: 4,
          textBorderType: 'solid'
        },
        roam: true,//是否开启鼠标缩放和平移漫游
        itemStyle: {
          areaColor: areaColor,//默认区块颜色
          borderColor: '#3479d8',//区块描边颜色
          borderWidth: 2,//区块描边
          // opacity: 0.6
        },
        emphasis: {//高亮状态下的多边形和标签样式。
          itemStyle: {
            areaColor: '#ff9100',//高亮状态区块颜色
            borderColor: '#3479d8',//区块描边颜色
            borderWidth: 2,//区块描边
            fontWeight: 'bold',
            // shadowColor: '#40caff',
            // shadowOffsetX: -6,
            // shadowOffsetY: -4,
            // shadowBlur: 0,
            // opacity: 0.6
          },
          focus: 'none',//在高亮图形时，是否淡出其它数据的图形已达到聚焦的效果。支持如下配置：none(默认) self
          label: {
            color: '#fff',
            fontWeight: 'bold',
            fontSize: 12,
            lineHeight: 14,
            // backgroundColor: 'transparent',
            textBorderColor: '#333',
            textBorderWidth: 4,
            textBorderType: 'solid'
          },
        },
        tooltip: {//鼠标移入
          trigger: 'item',
          padding: 12,
          textStyle: {
            color: '#333'
          },
          formatter: function (params) {
            let obj = rank.list.find((v: any) => v.townName === params.name) as any
            return `
              <div class="my-map-tooltip">
                <div class="my-map-tooltip__title"><i></i><span>${obj.townName}</span></div>
                <div class="my-map-tooltip__info"><i></i><span>总户数：</span>${obj.totalNum}</div>
                <div class="my-map-tooltip__info"><i></i><span>上门总户数：</span>${obj.totalIntoNum}</div>
                <div class="my-map-tooltip__info"><i></i><span>入户率：</span>${obj.intoRate}</div>
              </div>`
          },
        },
        projection: {
          project: (point) => [point[0] / 180 * Math.PI, -Math.log(Math.tan((Math.PI / 2 + point[1] / 180 * Math.PI) / 2))],
          unproject: (point) => [point[0] * 180 / Math.PI, 2 * 180 / Math.PI * Math.atan(Math.exp(point[1])) - 90]
        },
        regions: regions
        // regions: [//对不同的区块进行着色
        //   {
        //     name: '双江口镇', //区块名称
        //     itemStyle: {
        //       areaColor: '#111',
        //     }
        //   }]
      },
    };
    echarts.registerMap('NX', geoJson) //注册
    myChart.setOption(optionMap);
    myChart.on('click', function (params) {
      // 控制台打印数据的名称
      let obj = rank.list.find((v: any) => v.townName === params.name) as any
      if (!obj.disabled) {
        router.push({ name: 'workbenchDetail', query: { townId: obj.townId, townName: obj.townName } })
      }
    });
    myChart.resize();
    loading.value = false
  })
}
onMounted(() => {
  loading.value = true
  onSortedList()
  window.addEventListener('resize', onResize)
})
const onResize = () => {
  resize.value = !resize.value
}
//浏览器是否变化
watch(
  () => resize.value,
  () => {
    let myChart = echarts.init(document.getElementById('main') as unknown as HTMLDivElement)
    myChart.resize()
  }
)

//前一天
const time = FunTime(new Date().getTime() - 24 * 60 * 60 * 1000)
// 详情
const onDetail = (item) => {
  if (!item.disabled) {
    router.push({ name: 'workbenchDetail', query: { townId: item.townId, townName: item.townName } })
  }
}
//注销之前
onBeforeUnmount(() => {
  let myChart = echarts.init(document.getElementById('main') as unknown as HTMLDivElement)
  myChart.dispose()
  window.removeEventListener('resize', onResize)
})
</script>
<style scoped lang='scss'>
.my-workbench {
  position: relative;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  background: url("../../assets/map_bg.jpg");
  padding: 20px;

  &__top {
    display: flex;
    line-height: 24px;
    font-size: 14px;
    color: #fff;
    width: 100%;
    padding: 18px 20px;
    box-sizing: border-box;
    background: $my-color-primary;
    border-radius: 8px;
    margin-bottom: 10px;

    >h3 {
      flex: 1;
      font-size: 24px;
      font-weight: bold;
      padding-left: 10px;
      border-left: 4px solid #fff;
    }
  }

  &__map {
    width: calc(100% - 340px);
    height: calc(100% - 70px);
    overflow: hidden;
    position: relative;

    &__map {
      width: 100%;
      height: 100%;
    }
  }

  &__rank,
  &__all {
    width: 240px;
    position: absolute;
    top: 100px;
    background: #f0f6ff;
    border-radius: 8px;

    >p {
      font-size: 16px;
      text-align: center;
      line-height: 1;
    }
  }

  &__rank {
    width: 340px;
    height: calc(100% - 120px);
    right: 20px;
  }

  &__all {
    left: 20px;

    >div {
      >ul {
        font-size: 14px;
        padding: 10px 20px;

        >li {
          overflow: hidden;

          >strong {
            float: right;
          }
        }
      }
    }
  }
}

.my-rank {
  height: 100%;
  line-height: 48px;

  >h3 {
    font-size: 16px;
    line-height: 18px;
    font-weight: bold;
    padding: 11px 15px;
    box-sizing: border-box;
    background: $my-color-primary;
    border-radius: 8px;

    >span {
      display: block;
      padding-left: 8px;
      border-left: 3px solid #fff;
      color: #fff;
    }
  }

  >dl {
    height: calc(100% - 40px);

    >dt {
      display: flex;
      font-weight: bold;
      color: $my-color-primary;

      >span {
        display: block;
        padding: 0 10px;
        font-size: 15px;
      }

      >span:first-child {
        flex: 1;
      }
    }

    >dd {
      width: 100%;
      height: calc(100% - 50px);
      overflow-y: scroll;
      font-size: 14px;

      >ul {
        >li {
          display: flex;

          >span {
            display: block;
            padding: 0 10px;
          }

          >span:first-child {
            flex: 1;
            cursor: pointer;

            &:hover {
              color: $my-color-primary;
            }
          }

          &:last-child {
            border-bottom: 0;
          }

          &:hover {
            background: #F0F6FF;
          }
        }

        >li.disabled {
          >span {
            color: #999;
            cursor: no-drop;
          }

          &:hover {
            background: #fff;
          }

          >span:first-child {
            &:hover {
              color: #999;
            }
          }
        }
      }
    }
  }
}
</style>
<style lang='scss'>
.my-map-tooltip {
  &__title {
    display: flex;
    font-size: 14px;

    >i {
      display: block;
      width: 4px;
      height: 10px;
      border-radius: 2px;
      background: #3479D8;
      margin: 5px 8px 0 0;
    }

    >span {
      display: block;
      line-height: 20px;
      font-weight: bold;
    }
  }

  &__info {
    display: flex;
    font-weight: bold;
    margin-top: 10px;

    >i {
      display: block;
      width: 4px;
      height: 4px;
      border-radius: 2px;
      background: #3479D8;
      margin: 8px 8px 0 0;
    }

    >span {
      display: block;
      line-height: 20px;
      font-weight: normal;
      font-size: 14px;
      width: 100px;
    }
  }
}
</style>